//
//  SettingViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-3-2.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "SettingViewController.h"
#import "UserSession.h"
#import "DXAlertView.h"
#import "UIImageView+MJWebCache.h"
#import "SettingLevel2ViewController.h"
#import "SVProgressHUD.h"
#import "AppsEngine.h"
#import "AppDelegate.h"

@interface SettingViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate,ImageUploadQueueDelegate> {
    DXAlertView *alertLogout;
    UIImagePickerController *photoPicker;
    NSString *avatarLink,*oldImageLink;
}
@end

@implementation SettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"设置"];
    [super customBackButton];
    
    UIButton* publishButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 30)];//
    [publishButton setImage:[UIImage imageNamed:@"btn_sure.png"] forState:UIControlStateNormal];
    [publishButton addTarget:self action:@selector(saveChanges) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initView];
    [APP_DELEGATE setImageUpoadQueueDelegate:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //释放delegate
    [APP_DELEGATE setImageUpoadQueueDelegate:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    NSDictionary *dict = [[UserSession shareUserSession] getUserPublicInfo];
    tfEnName.text = [dict objectForKey:@"enName"];
    tfUserName.text = [dict objectForKey:@"nickName"];
    if ([[dict objectForKey:@"sex"] isEqualToString:@"male"]) {
        //男性
        btnMale.selected = YES;
        btnFemale.selected = NO;
    }
    else {
        //女性
        btnMale.selected = NO;
        btnFemale.selected = YES;
    }
    avatarLink = [dict objectForKey:@"avatar"];
    oldImageLink = avatarLink;
    [imgvAvatar setImageURLStr:avatarLink placeholder:Default_Avatar];
    
//    labelTeamName.text = [dict objectForKey:@"teamName"];
    labelTeamName.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"motto"];
    [imgvTeamLogo setImageURLStr:[dict objectForKey:@"teamLogo"] placeholder:[UIImage imageNamed:@"default_team_logo.png"]];
    
}

- (NSString*)getUserAvatarSavedName {
    //avatar_[userId]_[sNo].suffix
    NSString *cLink = [NSString stringWithFormat:@"avatar_%@_%@.png",
                       [[UserSession shareUserSession] getUserId],
                       getRandomStrings(5)];
    return cLink;
}

- (void)saveChanges {
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[UserSession shareUserSession] getUserPublicInfo]];
    [dict setObject:tfUserName.text forKey:@"nickName"];
    [dict setObject:btnMale.selected ? @"male" : @"female" forKey:@"sex"];
    if (avatarLink) {
        [dict setObject:avatarLink forKey:@"avatar"];
    }
    [[UserSession shareUserSession] savePublicInfo:dict];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[dict objectForKey:@"nickName"],@"nickName",
                                   [dict objectForKey:@"sex"],@"sex",
                                   [[UserSession shareUserSession] getUserId],@"userId",
                                   [dict objectForKey:@"avatar"],@"avatar",nil];
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfModifyUserInfo" param:params onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            [SVProgressHUD showSuccessWithStatus:@"资料修改保存成功!"];
        }
        else {
            DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"资料修改保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
            alertView.rightBlock = ^(void) {
                [self saveChanges];
            };
            [alertView show];
        }
    } onError:^(NSError *error) {
        DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"资料修改保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
        alertView.rightBlock = ^(void) {
            [self saveChanges];
        };
        [alertView show];
    } method:@"GET"];
}


- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 101) {
        //更换头像
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"用相机拍一张",@"从相册选一张", nil];
        [actionSheet showInView:self.view];
    }
    else if (btn.tag == 102) {
        // 男
        btnFemale.selected = NO;
        btnMale.selected = YES;
    }
    else if (btn.tag == 103) {
        // 女
        btnFemale.selected = YES;
        btnMale.selected = NO;
    }
    else if (btn.tag == 111) {
        //球队
        SettingLevel2ViewController *l2Vc = [[SettingLevel2ViewController alloc] init];
        [self.navigationController pushViewController:l2Vc animated:YES];
    }
    else if (btn.tag == 112) {
        //绑定账号
    }
    else if (btn.tag == 200) {
        //注销
        alertLogout = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"您确定要注销登陆？" leftButtonTitle:@"否" rightButtonTitle:@"是"];
        alertLogout.rightBlock = ^(void){
            NSLog(@"about to log out");
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_user_logout object:nil];
        };
        [alertLogout show];
        
    }
    else if (btn.tag == 300) {
        //完成编辑
        [tfUserName resignFirstResponder];
        [tfEnName resignFirstResponder];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        //相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;  //是否可编辑
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            photoPicker = picker;
            [self presentModalViewController:photoPicker animated:YES];
        }else{
            //如果没有提示用户
            [SVProgressHUD showErrorWithStatus:@"您的设备不支持拍照!"];
        }
    }
    else if (buttonIndex == 1) {
        //相册
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        photoPicker = picker;
        [self presentModalViewController:photoPicker animated:YES];
    }
    NSLog(@"ActionSheel selected:No.%d",buttonIndex);
}


#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//[self saveAndResizeImage:image asName:@"tmp.png"]
        dispatch_async(dispatch_get_main_queue(), ^{
            //tb reload
            [imgvAvatar setImage:image];
            labelStatus.text = @"正在上传0%";
        });
        
        NSString *qiniuSavedName = [self getUserAvatarSavedName];
        NSString *imgTmpPath = saveAndResizeImage(image, qiniuSavedName,200);
        
        avatarLink = [NSString stringWithFormat:@"%@/%@",Qiniu_Backet_Domain,qiniuSavedName];
//        [imgUploader uploadImage:imgTmpPath asName:qiniuSavedName];
        
        [APP_DELEGATE uploadImageWithArray:[[NSArray alloc] initWithObjects:[NSString stringWithFormat:@"GF-Document:%@",imgTmpPath], nil] saveNameList:[[NSArray alloc] initWithObjects:qiniuSavedName, nil] submitToSinaPaarms:nil];
    });
    
    //图片存入相册
//    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [self dismissModalViewControllerAnimated:YES];
}

//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - ImageUploadQueueDelegate
- (void)ImageUploadQueueItemSuccess:(NSString *)filePath ret:(NSDictionary *)ret {
    labelStatus.text = @"点击更换头像";
    [self saveChanges];
}
- (void)ImageUploadQueueItemFail:(NSString *)filePath error:(NSError *)error {
    [SVProgressHUD showErrorWithStatus:@"上传失败!"];
    [imgvAvatar setImageURLStr:oldImageLink placeholder:Default_Avatar];
    labelStatus.text = @"点击更换头像";
}
- (void)ImageUploadQueueItemProcessUpdated:(NSString *)filePath percent:(float)percent {
    labelStatus.text = [NSString stringWithFormat:@"上传%.1f%%",percent*100];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    textField.inputAccessoryView = viewDoneEditting;
    return YES;
}

@end
